#include<iostream>
using namespace std;
#pragma once 
#include<string>
#include<unistd.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<cstring>
#define BACKLOG 5
class TcpServer
{
  private: 
    int port;
    int lsockfd;//监听套接字
  public:
    TcpServer(int _port)
      :port(_port)
      ,sockfd(-1)
    {}
    bool InitTcpServer()
    {
      lsockfd=socket(AF_INET,SOCK_STREAM,0);
      if(sockfd<0)
      {
        cerr<<"socket error"<<endl;
        return false;
      }
      struct sockaddr_in local;
      memset(&local,0,sizeof(local));
      local.sin_family=AF_INET;
      local.sin_port=htons(port);
      local.sin_addr.s_addr=INADDR_ANY;
      if(bind(lsockfd,(struct sockaddr*)& local,sizeof(local))<0)
      {
        cerr<<"bind error"<<endl;
        return false;
      }
      if(listen(lsockfd,BACKLOG)<0)
      {
        cerr<<"listen error"<<endl;
        return false;
      }
      return true;
    }     
    void Loop()
    {
      int sockfd;
      for(;;)
      {
        struct sockaddr_in peer;
        socklen_t len=sizeof(peer);
         sockfd=accept(lsockfd,(struct sockaddr*)& peer,&len);
        if(sockfd<0)
        {
          cout<<"accept error"<<endl;
          continue;//获取连接失败
          //继续监听
          continue;
        }
      }
      cout<<"get a new link:"<<sockfd<<endl;
    }
};
